package com.yonyou.crm.bpub.refervalue.service;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.yonyou.crm.bpub.refervalue.entity.ReferDataVO;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class RefervalueBizServiceImpl {

	@Autowired
	private ApplicationContext applicationContext; 

	@SuppressWarnings("unchecked")
	public <T extends Serializable> Map<String, Object> getRefervalues(Page<T> page, Map<String, Object> paraMap) {

		List<ReferDataVO> list = new ArrayList<ReferDataVO>();

		Long tenantId = new Long(InvocationInfoProxy.getTenantid());
		paraMap.put("tenantId", tenantId);
		/*
		Long orgId = new Long(InvocationInfoProxy.getParameter("orgid"));
		paraMap.put("orgId", orgId);
		// TODO 加权限
		Long userId = new Long(InvocationInfoProxy.getParameter("id"));
		paraMap.put("userId", userId);
		*/

		String refertype = (String)paraMap.get("refertype");
		String className = "";
		refertype = refertype.substring(0, 1).toUpperCase() + refertype.substring(1);

		//if (refertype.equals("Account")) {
			//className = "com.yonyou.crm.bpub.refervalue.service." + "CustomerRefervalue";
		//} else {
			className = "com.yonyou.crm.bpub.refervalue.service." + refertype + "Refervalue";
		//}

		try{
			Class<?> serviceClass = Class.forName(className);
			Constructor<?> serviceConstructor = serviceClass.getConstructor();
			Object service = serviceConstructor.newInstance();
			Method getRefervalues = serviceClass.getMethod("getRefervalues", Page.class, Map.class);
			applicationContext.getAutowireCapableBeanFactory().autowireBean(service);
			list = (List<ReferDataVO>)getRefervalues.invoke(service,(Page<T>)page, paraMap);
		} catch (Exception e) {
			throw new CrmBusinessException("参照服务端错误", e);
		}

		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("datalist", list);
		return rsMap;
	}
}
